#include "d_png.h"

#include <png.h>
#include <zlib.h>



unsigned int blend[640*360];

void png_blend(struct filename_postion *file , int count_file){
	int i;
	int j;	

	png_image image;
	memset(&image, 0, (sizeof image));


      	image.version = PNG_IMAGE_VERSION;

	for(i=0;i<640*360;i++){
		blend[i]=0;
	}


	for(i=0;i<count_file;i++){

	   if(png_image_begin_read_from_file(&image, file[i].file_name ) != 0){
		png_bytep buffer;
		image.format = PNG_FORMAT_RGBA;
		buffer = malloc(PNG_IMAGE_SIZE(image));

		if (buffer != NULL && png_image_finish_read(&image, NULL/*background*/, buffer, 0/*row_stride*/, NULL/*colormap*/) != 0){
			// printf("width %d height %d\n",image.width,image.height);
			
			unsigned int *dst;
			unsigned int *src;

			for(int j=0; j<image.height; j++){
				dst = blend + (file[i].y_base + j ) * 640 + file[i].x_base;
                src = (unsigned int *)(buffer + j*image.width*4);
				unsigned char alpha;
				unsigned char R1,R2,B1,B2,G1,G2,R,G,B;
				for(int k=0; k<image.width; k++){
					alpha =  *(src + k) >>24 ;

					if( alpha ) {
						R1=(*(src+k) & 0x00FF0000)>>16;
						R2=(*(dst+k) & 0x00FF0000)>>16;
						B1=(*(src+k) & 0x0000FF00) >> 8;  
						B2=(*(dst+k) & 0x0000FF00) >> 8;
						G1=(*(src+k) & 0x000000FF) ;  
						G2=(*(dst+k) & 0x000000FF);

						R=(alpha*R1 +(255-alpha)*R2) >>8;
						G=(alpha*G1 +(255-alpha)*G2) >>8;
						B=(alpha*B1 +(255-alpha)*B2) >>8;
						
						*(dst + k) = 0xFF << 24 | R <<16 | B <<8 | G ;
					}
				}

				
			}		
				
		}

		free(buffer);
	  }
	

       }
	
}



void png_display(unsigned int *fb_base , int x_base, int y_base)
{
	unsigned int *src;
	unsigned int *dst;
	int i;

	unsigned int *buffer = (unsigned int *)blend;
	for(int i=0;i<360;i++){
		dst = fb_base + (y_base+i)*1920 + x_base; 			
		src = (unsigned int *)(buffer + i*640);


		memcpy(dst,src,640*4);
	}

}

